from rest_framework import serializers

from oauth.utils import check_access_token
from users.models import User
from .models import OAuthQQUser
from django_redis import get_redis_connection
# serializers.ModelSerializer
# serializers.Serializer
#ModelSerializer没有优势,所以用Serializer

class OauthQQUserSerializer(serializers.Serializer):

    """
    2.校验数据(手机号,密码,短信验证码,openid(处理过的))
        2.1短信验证码
        2.2openid(处理过的)
        2.3根据手机号查询用户信息,判断用户是否存在
    """
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')


    def validate(self, attrs):
        # 1.短信验证码
        #1.1用户提交的
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        #1.2取出redis中的短信验证码
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s'%mobile)
        if redis_code is None:
            raise serializers.ValidationError('短信验证码已过期')

        #1.3将二者进行对比
        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码不一致')

        # 2.openid(处理过的)
        access_token = attrs.get('access_token')

        openid = check_access_token(access_token)
        if openid is None:
            raise serializers.ValidationError('token被篡改')

        attrs['openid'] = openid
        # 3.根据手机号查询用户信息,判断用户是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:

            #如果用户不存在,就创建用户
            #我们可以在这里创建user
            #我们把创建user的工作留到后边
            pass
        else:
            #如果用户存在,就校验密码
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user

        return attrs

    #data -->attrs -->validated_data
    def create(self, validated_data):

        user = validated_data.get('user')
        openid = validated_data.get('openid')

        if user is None:
            #创建用户
            user = User.objects.create(
                username = validated_data.get('mobile'),
                mobile = validated_data.get('mobile'),
                password = validated_data.get('password')
            )

            user.set_password(validated_data.get('password'))
            user.save()

        qquser = OAuthQQUser.objects.create(
            user = user,
            openid = openid
        )

        return qquser







